<!-- 更新角色 -->
<template>
  <cfDialog :dialogObj='dialogObj'>
    <div slot='content' v-loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey" label-width="108px">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <span>权限字符</span>
          </span>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状 态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sysNormalDisable" :key="dict.dictValue" :label="dict.dictValue" >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备 注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template slot='footer'>
      <el-button type='primary' size='small' v-if="!loading" @click='handleConfirm'>确定</el-button>
    </template>
  </cfDialog>
</template>
<script>
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from "@/api/system/role";
export default {
  props: {
    dialogObj: {
      type: Object,
      default: ({
        visible: false,
        type: '',
        id: '',
        title: '',
        width: '528px'
      })
    }
  },
  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      menuOptions: [], /**菜单列表 */
      defaultProps: {
        children: "children",
        label: "label"
      },
      form: {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      },
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      loading: false
    }
  },
  created() {
    this.getSysNormalDisable();
    this.getMenuTreeselect();
    this.dialogObj.id && this.getRoleDetail();
  },
  methods: {
    /** 修改按钮操作 */
    async getRoleDetail() {
      this.loading = true;
      const roleId = this.dialogObj.id; 
      const res = await getRole(roleId);
      if(res.code == 200) {
        this.form = res.data;
        this.$nextTick(async () => {
          const result = await this.getRoleMenuTreeselect(roleId);
          if(result.code == 200) {
            let checkedKeys = result.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(v, true ,false);
              })
            })
          }
          setTimeout(() => {
            this.loading = false;
          }, 500);
        });
      } else {
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(res => {
        this.menuOptions = res.menus;
        return res;
      });
    },
    /**确定按钮提交功能*/
    handleConfirm() {
      this.submitForm('form', async () => {
        this.loading = true;
        let res = null;
        if (this.form.roleId != undefined) {
          this.form.menuIds = this.getMenuAllCheckedKeys();
          res = await updateRole(this.form);
        } else {
          this.form.menuIds = this.getMenuAllCheckedKeys();
          res = await addRole(this.form);
        }
        if(res.code == 200) {
          this.$modal.msgSuccess("新增成功");
          this.dialogObj.visible = false;
          this.$emit('refresh');
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 查询菜单树结构 */
    async getMenuTreeselect() {
      const res = await menuTreeselect();
      if(res.code == 200) {
        this.menuOptions = res.data;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
  }
}
</script>